<template>
  <div class="app-container calendar-list-container">
    <basic-container>
      <template>
        <el-tabs @tab-click="switchTab">
          <el-tab-pane label='信息管理' name='userManager'/>
          <el-tab-pane label='密码管理' name='passwordManager'/>
          <el-tab-pane label='第三方账号管理' name='thirdManager'/>
        </el-tabs>
      </template>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form :model="ruleForm2"
                     :rules="rules2"
                     ref="ruleForm2"
                     label-width="100px"
                     v-if="switchStatus==='userManager'"
                     class="demo-ruleForm">
              <el-form-item label="用户名"
                            prop="username">
                <el-input type="text"
                          v-model="ruleForm2.username"
                          disabled></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="ruleForm2.phone" placeholder="验证码登录使用"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary"
                           @click="submitForm('ruleForm2')">提交
                </el-button>
                <el-button @click="resetForm('ruleForm2')">重置</el-button>
              </el-form-item>
            </el-form>
            <el-form :model="ruleForm2"
                     :rules="rules2"
                     ref="ruleForm2"
                     label-width="100px"
                     v-if="switchStatus==='passwordManager'"
                     class="demo-ruleForm">
              <el-form-item label="原密码"
                            prop="password">
                <el-input type="password"
                          v-model="ruleForm2.password"
                          auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="密码"
                            prop="newpassword1">
                <el-input type="password"
                          v-model="ruleForm2.newpassword1"
                          auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="确认密码"
                            prop="newpassword2">
                <el-input type="password"
                          v-model="ruleForm2.newpassword2"
                          auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary"
                           @click="submitForm('ruleForm2')">提交
                </el-button>
                <el-button @click="resetForm('ruleForm2')">重置</el-button>
              </el-form-item>
            </el-form>
            <div v-if="switchStatus==='thirdManager'">
              <el-table
                :data="tableData"
                border
                style="width: 100%">
                <el-table-column
                  type="index"
                  width="50">
                </el-table-column>
                <el-table-column
                  prop="oauthTypeDesc"
                  label="绑定帐号信息"
                  align="center"
                  :formatter="iconFormatter"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="oauthStatusDesc"
                  label="状态"
                  align="center"
                  width="180">
                  <template slot-scope="scope">
                    <el-tag
                      type="primary"
                      disable-transitions>{{scope.row.oauthStatusDesc}}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="action"
                  label="操作">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      @click="removeBind(scope.$index, scope.row)">解除绑定
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div>
                <el-row>
                  你还可以绑定以下第三方帐号
                </el-row>
                <el-row>
                  <el-button v-if="showWechat" @click="bindThird('wechat')" icon="icon-social-wechat"
                             circle></el-button>
                  <el-button v-if="showQQ" type="primary" @click="bindThird('tencent')" icon="icon-social-qq"
                             circle></el-button>
                  <el-button v-if="showWeibo" type="success" @click="bindThird('weibo')" icon="icon-social-weibo"
                             circle></el-button>
                </el-row>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </basic-container>
  </div>
</template>


<script>
  import {openWindow} from '@/util/util';
  import {handleDown, unbindThirdAuth} from "@/api/admin/user";
  import {mapState} from 'vuex';
  import store from "@/store";
  import request from '@/router/axios';
  import {validatenull} from "@/util/validate";
  import {Message} from 'element-ui';

  export default {
    data() {
      var validatePass = (rule, value, callback) => {
        if (this.ruleForm2.password !== '') {
          if (value !== this.ruleForm2.newpassword1) {
            callback(new Error('两次输入密码不一致!'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return {
        switchStatus: '',
        avatarUrl: '',
        show: false,
        headers: {
          Authorization: 'Bearer ' + store.getters.access_token
        },
        ruleForm2: {
          username: '',
          password: '',
          newpassword1: '',
          newpassword2: '',
          avatar: '',
          phone: ''
        },
        rules2: {
          password: [{required: true, min: 6, message: '原密码不能为空且不少于6位', trigger: 'change'}],
          newpassword1: [{required: false, min: 6, message: '不少于6位', trigger: 'change'}],
          newpassword2: [{required: false, validator: validatePass, trigger: 'blur'}]
        },
        tableData: [],
        showWechat: true,
        showQQ: true,
        showWeibo: true,
      }
    },
    created() {
      this.ruleForm2.username = this.userInfo.username
      this.ruleForm2.phone = this.userInfo.phone
      this.switchStatus = 'userManager'
      this.tableData = this.socialInfos;
    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo,
        socialInfos: state => state.user.socialInfos
      }),
    },
    watch: {
      route() {
        const params = this.$route.params;
        console.log("watch");
        console.log(params);
        console.log("watch");
        if (!validatenull(params.code)) {
          if (validatenull(params.oauthId)) {
            Message({
              message: "不支持的第三方登陆",
              type: "error"
            });
            return;
          }
        }
      }
    },
    methods: {
      switchTab(tab, event) {
        this.switchStatus = tab.name
      },
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            request({
              url: '/admin/user/edit',
              method: 'put',
              data: this.ruleForm2
            }).then(response => {
              if (response.data.data) {
                this.$notify({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
                // 修改密码之后强制重新登录
                if (this.switchStatus === 'passwordManager') {
                  this.$store.dispatch('LogOut').then(() => {
                    location.reload() // 为了重新实例化vue-router对象 避免bug
                  })
                }
              } else {
                this.$notify({
                  title: '失败',
                  message: response.data.msg,
                  type: 'error',
                  duration: 2000
                })
              }
            }).catch(() => {
              this.$notify({
                title: '失败',
                message: '修改失败',
                type: 'error',
                duration: 2000
              })
            })
          } else {
            return false
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      iconFormatter(row, column) {
        this.hideBindThirdIcon(row.oauthType);
        return row.oauthTypeDesc;
      },
      showBindThirdIcon(oauthType) {
        if (oauthType == "WEIBO") {
          this.showWeibo = true;
        }
        if (oauthType == "WECHAT") {
          this.showWechat = true;
        }
        if (oauthType == "QQ") {
          this.showQQ = true;
        }
      },
      hideBindThirdIcon(oauthType) {
        if (oauthType == "WEIBO") {
          this.showWeibo = false;
        }
        if (oauthType == "WECHAT") {
          this.showWechat = false;
        }
        if (oauthType == "QQ") {
          this.showQQ = false;
        }
      },
      removeBind(index, row) {
        this.$confirm('解绑后将无法使用该第三方帐号登录', '解绑提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          unbindThirdAuth(row.oauthId).then(response => {
            if (response.data.data) {
              this.showBindThirdIcon(row.oauthType);
              this.$message({
                type: 'success',
                message: '解绑成功!'
              });
              this.deleteTabelRow(index);
            } else {
              this.$notify({
                title: '失败',
                message: '解绑失败!',
                type: 'error',
                duration: 2000
              })
            }
          })
        });
      },
      bindThird(thirdpart) {
        let appid, client_id, redirect_uri, url
        redirect_uri = encodeURIComponent(window.location.origin + '/#/authredirect')
        if (thirdpart === 'wechat') {
          appid = 'xxxx'
          url = 'https://open.weixin.qq.com/connect/qrconnect?appid=' + appid + '&redirect_uri=' + redirect_uri + '&state=WECHAT_BIND&response_type=code&scope=snsapi_login#wechat_redirect'
        } else if (thirdpart === 'tencent') {
          client_id = 'xxxx'
          url = 'https://graph.qq.com/oauth2.0/authorize?response_type=code&state=QQ_BIND&client_id=' + client_id + '&redirect_uri=' + redirect_uri
        } else if (thirdpart === 'weibo') {
          client_id = '3646475573'
          url = 'https://api.weibo.com/oauth2/authorize?state=WEIBO_BIND&client_id=' + client_id + '&redirect_uri=' + redirect_uri
        }
        openWindow(url, thirdpart, 540, 540);
      },
      deleteTabelRow(index) {
        this.tableData.splice(index, 1)
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px !important;
    color: #8c939d !important;
    width: 178px !important;
    height: 178px !important;
    line-height: 178px !important;
    text-align: center !important;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .el-row {
    margin-bottom: 20px;

  &
  :last-child {
    margin-bottom: 0;
  }

  }
</style>
